package com.horay.nettydemo.nio.file;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.unit.DataSize;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 写入文件
 *
 * @author heyingcheng
 * @date 2019/11/23 21:10
 */
@Slf4j
public class WriteAndReadFile {

    private static final String PATH_NAME = "D:/hello.txt";

    public static void main(String[] args) {
        String value = "Hello,赫英成";
        try (FileOutputStream fileOutputStream = new FileOutputStream(PATH_NAME)) {
            FileChannel channel = fileOutputStream.getChannel();

            ByteBuffer byteBuffer = ByteBuffer.allocate(Math.toIntExact(DataSize.ofBytes(64L).toBytes()));
            byteBuffer.put(value.getBytes());

            byteBuffer.flip();

            channel.write(byteBuffer);
        } catch (FileNotFoundException e) {
            log.error("写入文件异常", e);
        } catch (IOException e) {
            log.error("写入文件异常", e);
        }

        log.info("写入文件完成");

        File file = new File(PATH_NAME);
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            FileChannel channel = fileInputStream.getChannel();

            ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
            channel.read(byteBuffer);

            byteBuffer.flip();

            log.info("文件内容:[{}]", new String(byteBuffer.array()));
        } catch (FileNotFoundException e) {
            log.error("读取文件异常", e);
        } catch (IOException e) {
            log.error("读取文件异常", e);
        }
    }

}
